package com.xuerhua.yxt.controller.sys.kccs;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;

import com.xuerhua.yxt.common.AdminUser;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.sun.xml.bind.v2.schemagen.xmlschema.Import;
import com.xuerhua.yxt.common.RspResult;
import com.xuerhua.yxt.common.enums.Status;
import com.xuerhua.yxt.controller.BaseController;
import com.xuerhua.yxt.dao.StuInfoMapper;
import com.xuerhua.yxt.excel.CellUtil;
import com.xuerhua.yxt.model.Grid;
import com.xuerhua.yxt.model.KccsCourseInfo;
import com.xuerhua.yxt.model.KccsStudentSign;
import com.xuerhua.yxt.model.StuInfo;
import com.xuerhua.yxt.model.StudentInfo;
import com.xuerhua.yxt.reqVo.KccsCourseQueryVO;
import com.xuerhua.yxt.reqVo.StudentReqVO;
import com.xuerhua.yxt.service.IKccsCourseInfoService;
import com.xuerhua.yxt.service.IStudentService;
import com.xuerhua.yxt.utils.ExcelExportUtil;
import com.xuerhua.yxt.utils.ExportSetInfoUtil;
import com.xuerhua.yxt.utils.StringUtil;

@RequestMapping("/sys/kccsCourse/special")
@Controller
public class SysKccsSpecialController extends BaseController {
	
	@Autowired
	private IKccsCourseInfoService kccsCourseInfoService;
	@Autowired
	private IStudentService studentService;
	
	@RequestMapping(value={"","/"})
	public String Index() {
		return "sys/kccsCourse/special";
	}
	
	@RequestMapping("pageQuery")
	@ResponseBody Object pageQuery(KccsCourseQueryVO vo){
		try {
			if(vo.getTermId() == null) {
				vo.setTermId(getCurrentTerm().getId());
			}
			vo.setCourseType(2);
			return kccsCourseInfoService.selectSignListByPage(vo);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	@RequestMapping("courseList")
	@ResponseBody Object courseList(KccsCourseQueryVO vo){
		try {
			vo.setCourseType(2);
			if(!StringUtil.isNotNullOrZero(vo.getSchoolId())){
				AdminUser adminUser = getAdminUser();
				vo.setSchoolId(adminUser.getTeacherInfo().getSchoolId());
			}
			return kccsCourseInfoService.selectList(vo);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	@RequestMapping("addUpdate")
	@ResponseBody Object addUpdate(KccsStudentSign vo) {
		try {
			vo.setTermId(getCurrentTerm().getId());
			kccsCourseInfoService.addSpecialSign(vo);
			return new RspResult(Status.SUCCESS);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return new RspResult(Status.FAIL);
	}
	
	@RequestMapping("del")
	@ResponseBody Object del(String delIds){
		try {
			kccsCourseInfoService.delStudentSignByIds(Arrays.asList(delIds.split(",")));
			return new RspResult(Status.SUCCESS);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return new RspResult(Status.FAIL);
	}
	
//	@RequestMapping("import")
//	@ResponseBody Object Import(@RequestParam(value="files")MultipartFile buildInfo) {
//		try {
//			// 创建一个FileInputStream 文件输入流
//	        InputStream inputStream = buildInfo.getInputStream();
//	    	// 创建对Excel工作簿文件的引用
//	        Workbook wookbook = null;
//	        String filename = buildInfo.getOriginalFilename();
//	        String fileType = filename.substring(filename.lastIndexOf(".") + 1,
//	        		filename.length());
//	        if (fileType.equals("xls")) {
//	        	try{
//	        		wookbook = new HSSFWorkbook(inputStream);
//	        	}catch(Exception e){
//	        		wookbook = null;
//	           	 	wookbook = new XSSFWorkbook(inputStream);
//	        	}
//	        }else{
//	       	 	wookbook = new XSSFWorkbook(inputStream);
//	        }
//	        List<StuInfo> list = new ArrayList<>();
//	        Integer termKey = getCurrentTerm().getTermKey();
//	        int sheetNum = wookbook.getNumberOfSheets();
//	        for(int k = 0; k < sheetNum; k++) {
//		        Sheet sheet = wookbook.getSheetAt(k);
//		        String sheelName = sheet.getSheetName();
//		        int coloumNum=sheet.getRow(1).getPhysicalNumberOfCells();// 获取总列数
//		        int rowNum=sheet.getPhysicalNumberOfRows();//获得总行数
//		        if(rowNum <= 1) {
//		        	return new RspResult(Status.TEMPLATE_DATA_NULL);
//		        }
//		        for (int i = 1; i < rowNum; i++) {
//		        	// 读取左上端单元格
//		            Row row = sheet.getRow(i);
//		            if (row != null) {
//		            	StuInfo stuInfo = new StuInfo();
//		            	int gradeId = Integer.valueOf(sheelName.substring(0, 1));
//	    				int clazz = Integer.valueOf(sheelName.substring(1, sheelName.length()));
//		            	stuInfo.setGrade(termKey.intValue() - gradeId + 1);
//		            	stuInfo.setClazz(clazz);
//	    				for(int j = 0; j < coloumNum; j ++) {
//		            		Cell cell = row.getCell((short)j);
//		            		if(cell != null) {
//		            			String val = CellUtil.getCellValue(cell);
//		            			if(j == 0) {
//		            				stuInfo.setStudentNum(Integer.valueOf(val));
//		            			} else if(j == 1) {
//		            				stuInfo.setStudentNo(val);
//		            			}else if(j == 2) {
//		            				stuInfo.setStudentName(val);
//		            			}
//		            		}
//		            	}
//		            	list.add(stuInfo);
//		            }
//		        }
//	        }
//	        stuInfoMapper.batchAdd(list);
//	        return new RspResult(Status.SUCCESS);
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//		return new RspResult(Status.FAIL);
//	}
	
	@RequestMapping("import")
	@ResponseBody Object courseImport(
			@RequestParam(value="courseId")Integer courseId,
			@RequestParam(value="files")MultipartFile buildInfo) {
		try {
			// 创建一个FileInputStream 文件输入流
	        InputStream inputStream = buildInfo.getInputStream();
	    	// 创建对Excel工作簿文件的引用
	        Workbook wookbook = null;
	        String filename = buildInfo.getOriginalFilename();
	        String fileType = filename.substring(filename.lastIndexOf(".") + 1,
	        		filename.length());
	        if (fileType.equals("xls")) {
	        	try{
	        		wookbook = new HSSFWorkbook(inputStream);
	        	}catch(Exception e){
	        		wookbook = null;
	           	 	wookbook = new XSSFWorkbook(inputStream);
	        	}
	        }else{
	       	 	wookbook = new XSSFWorkbook(inputStream);
	        }
	        // 在Excel文档中，第一张工作表的缺省索引是0
	        Sheet sheet = wookbook.getSheetAt(0);
	        int coloumNum=sheet.getRow(1).getPhysicalNumberOfCells();// 获取总列数
	        int rowNum=sheet.getPhysicalNumberOfRows();//获得总行数
	        if(rowNum <= 1) {
	        	return new RspResult(Status.TEMPLATE_DATA_NULL);
	        }
	        List<KccsStudentSign> list = new ArrayList<>();
	        List<String> errorList = new ArrayList<>();
	        // 遍历行 从第三行开始遍历
	        for (int i = 1; i < rowNum; i++) {
	        	// 读取左上端单元格
	            Row row = sheet.getRow(i);
	            if (row != null) {
	            	for(int j = 0; j < coloumNum; j ++) {
	            		Cell cell = row.getCell((short)j);
	            		if(cell != null) {
	            			String val = CellUtil.getCellValue(cell);
	            			if(StringUtils.isBlank(val)) {
	            				errorList.add("第" + (i + 1) + "行第" + (j + 1) + "列的值为空");
	            				break;
	            			}
	            		}
	            	}
	            }
	        }
	        if(!StringUtil.isNullOrEmpty(errorList)) {
	        	return new RspResult(Status.FAIL.getCode(), String.join(",", errorList));
	        }
	        KccsCourseInfo courseInfo = kccsCourseInfoService.selectByPrimaryKey(courseId);
	        Integer termKey = getCurrentTerm().getTermKey();
	        Integer termId = getCurrentTerm().getId();
	        for (int i = 1; i < rowNum; i++) {
	        	// 读取左上端单元格
	            Row row = sheet.getRow(i);
	            if (row != null) {
	            	StudentReqVO studentReqVO = new StudentReqVO();
	            	for(int j = 0; j < coloumNum; j ++) {
	            		Cell cell = row.getCell((short)j);
	            		if(cell != null) {
	            			String val = CellUtil.getCellValue(cell);
	            			if(j == 0) {
	            				int gradeId = Integer.valueOf(val.substring(0, 1));
	            				int clazz = Integer.valueOf(val.substring(1, val.length()));
	            				studentReqVO.setGrade(termKey.intValue() - gradeId + 1);
	            				studentReqVO.setClazz(clazz);
	            			} else if(j == 1) {
	            				studentReqVO.setStudentName(val);
	            			}
	            		}
	            	}
	            	List<StudentInfo> studentList = studentService.selectListByParam(studentReqVO);
	            	if(!StringUtil.isNullOrEmpty(studentList)) {
            			KccsStudentSign sign = new KccsStudentSign();
	            		sign.setCourseId(courseInfo.getId());
	            		sign.setStudentId(studentList.get(0).getId());
	            		sign.setTermId(termId);
            			list.add(sign);
	            	}
	            }
	        }
	        if(StringUtil.isNullOrEmpty(list)) {
	        	return new RspResult(Status.TEMPLATE_DATA_NULL);
	        }
	        kccsCourseInfoService.batchAddStudentSign(list);
	        return new RspResult(Status.SUCCESS);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return new RspResult(Status.TEMPLATE_ERROR);
	}
	
	@RequestMapping("export")
	ModelAndView workSignExport(KccsCourseQueryVO vo) {
		ModelAndView modelAndView = new ModelAndView();
		try {
			if(vo.getTermId() == null) {
				vo.setTermId(getCurrentTerm().getId());
			}
			vo.setRows(Integer.MAX_VALUE - 1);
			vo.setCourseType(2);
			Grid grid = kccsCourseInfoService.selectSignListByPage(vo);
			//数据源
			LinkedHashMap<String, List> map = new LinkedHashMap<String, List>();
			String title="特长班学生名单";
			map.put(title, grid.getRows());
			
			//标题  和  标题变量
		    List<String[]> headNames = new ArrayList<String[]>();
		    headNames.add(new String[] { "年级","班号","学生姓名","证件类型","证件号","性别","课程名称","上课时间","上课教师"});
		    List<String[]> fieldNames = new ArrayList<String[]>();
		    fieldNames.add(new String[] { "gradeName","clazz","studentName","studentIdNoType","studentIdNo","studentSex","courseName","classDate","classTeacher"});
		    
		    //excel生成帮助类
		    List<Integer[]> columnFormat=new ArrayList<Integer[]>();
		    Integer [] format=new Integer[22];
		    columnFormat.add(format);
		    
		    String [] titles=new String[] {title};
		    //excel生成帮助类
		    ExportSetInfoUtil setInfo = new ExportSetInfoUtil(map,titles,headNames,fieldNames,columnFormat);
		    request.setAttribute("exportDatas", setInfo);
		    
		    //生成
			modelAndView=new ModelAndView(new ExcelExportUtil(title+".xls",""));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return modelAndView;
	}
	
}
